package com.car.loan.common.utils.ip;

import com.car.loan.common.utils.http.OkHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.car.loan.common.utils.StringUtils;
import com.car.loan.common.utils.http.HttpUtils;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class AddressUtils {

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "http://ip.ws.126.net/ipquery";

    public static String getRealAddressByIP(String ip) {
//        String address = "XX XX";
//        // 内网不查询
//        if (IpUtils.internalIp(ip)) {
//            return "内网IP";
//        }
//        String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip);
//        if (StringUtils.isEmpty(rspStr)) {
//            log.error("获取地理位置异常 {}", ip);
//            return address;
//        }
//        JSONObject obj = JSONObject.parseObject(rspStr);
//        JSONObject data = obj.getObject("data", JSONObject.class);
//        String region = data.getString("region");
//        String city = data.getString("city");
//        address = region + " " + city;
        return getRealAddressBy126IP(ip);
    }

    public static String getRealAddressBy126IP(String ip) {
        String address = "XX XX";
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        String s = OkHttpUtil.get("http://ip.ws.126.net/ipquery?ip=39.185.200.214");
        if (StringUtils.isNotEmpty(s)) {
            String[] split = s.split(";");
            String s1 = split[0];
            String[] split1 = s1.split(",");
            String lo = split1[0];
            String region = lo.substring(lo.indexOf("\"") + 1, lo.lastIndexOf("\""));
            String lc = split1[1];
            String city = lc.substring(lc.indexOf("\"") + 1, lc.lastIndexOf("\""));
            address = region + " " + city;
            return address;
        } else {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
    }


    public static void main(String[] args) {
        //var lo="浙江省", lc="宁波市"; var localAddress={city:"宁波市", province:"浙江省"}
        String s = OkHttpUtil.get("http://ip.ws.126.net/ipquery?ip=39.185.200.214");
        if (StringUtils.isNotEmpty(s)) {
            String[] split = s.split(";");
            String s1 = split[0];
            String[] split1 = s1.split(",");
            String lo = split1[0];
            String substring = lo.substring(lo.indexOf("\"") + 1, lo.lastIndexOf("\""));
            String lc = split1[1];
            String substring2 = lc.substring(lc.indexOf("\"") + 1, lc.lastIndexOf("\""));
            System.out.println(substring2);
        }
    }
}
